package john.wenzi.server.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import john.wenzi.server.entity.FileUploadEntity;
import john.wenzi.server.service.Impl.FileUploadServiceImpl;
import john.wenzi.server.utils.AESUtil;
import john.wenzi.server.utils.RSAUtil;

public class UploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	public static Logger logger = LoggerFactory.getLogger(UploadServlet.class);
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.info("上传文件开始");
		request.setCharacterEncoding("utf-8"); 
	    response.setCharacterEncoding("utf-8");
	    //获取公钥
	    File publicFile = new File("ppk/public.ppk");
	    Long filelength = publicFile.length();
        byte[] fileByte = new byte[filelength.intValue()];
        FileInputStream is = new FileInputStream(publicFile);
        is.read(fileByte);
        String publicKey = new String(fileByte);
		//设置目录
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String uploadPath = "files/" + sdf.format(new Date());
	    File uploadFile = new File(uploadPath);
	    if (!uploadFile.exists()) {
	      uploadFile.mkdirs();
	    }
	    
	    //检测是不是存在上传文件 
	    boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
	    if(isMultipart){
	    	//文件上传实体类
	    	FileUploadEntity fileUploadEntity = new FileUploadEntity();
	    	DiskFileItemFactory factory = new DiskFileItemFactory(); 
	    	ServletFileUpload upload = new ServletFileUpload(factory); 
		    upload.setHeaderEncoding("UTF-8");
		    List<FileItem> items = null; 
		    try { 
		      // 解析request请求 
             items = upload.parseRequest(request); 
		    } catch (FileUploadException e) { 
		  	  logger.info("解析request请求出现异常："+e.getMessage());
		      e.printStackTrace(); 
		    } 
		      
		    if(items != null && items.size() > 0){ 
	    	 FileItem item = items.get(0);
	    	  // 获得上传文件的文件名
	          String fileName = item.getName(); 
	          fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
	          fileUploadEntity.setFileName(fileName);
	          //文件大小
	          long fileSize = item.getSize();
	          //文件类型
	          String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
	          String uuid = UUID.randomUUID().toString();
	          String uuidName = uuid+"."+fileType;
	          File file = new File(uploadPath+"/"+uuidName);
	          try { 
	            item.write(file); 
	            //获取密钥
	            String key =  AESUtil.getGenerateKey();
	            //加密文件
	            File f1 = AESUtil.encrypt(file,"txt",key);
	            FileUtils.copyFile(f1, file);
	            //删除临时文件
	            f1.delete();
	            //加密密钥
	            String encryptKey = RSAUtil.encrypt(key, publicKey);
	              
	            fileUploadEntity.setFileSize(String.format("%.2f" , (fileSize+0.0)/1024) + "KB");
	            fileUploadEntity.setFileType(fileType);
	            fileUploadEntity.setFilePath(uploadPath);
	            fileUploadEntity.setUuidName(uuidName);
	            fileUploadEntity.setEncryptDigitalEnvelope(encryptKey);
		        fileUploadEntity.setCreateDate(new Date());
		        fileUploadEntity.setStatus("1");
		        FileUploadServiceImpl fileUploadServiceImpl = new FileUploadServiceImpl();
		        //插入文件信息至数据库
		        fileUploadServiceImpl.insertUploadRecord(fileUploadEntity);
		        //返回重命名
		        response.getWriter().write(uuidName);
		        logger.info("上传文件成功");
	          } catch (Exception e) { 
	        	logger.info("上传文件出现异常："+e.getMessage());
	            e.printStackTrace(); 
	          }
	            
		    } 
	    } 
	}

}
